//
//  NIMMessagCell.m
//  meiyinxiang
//
//  Created by 陈李飞 on 2017/11/2.
//  Copyright © 2017年 hbjApple. All rights reserved.
//

#import "NIMMessagCell.h"
#import "NIMMessageModel.h"
#import "NIMAvatarImageView.h"
#import "NIMBadgeView.h"
#import "NIMSessionMessageContentView.h"
#import "NIMKitUtil.h"
#import "NIMSessionAudioContentView.h"
#import "UIView+NIM.h"
#import "NIMKitUIConfig.h"
#import "NIMKitDependency.h"
#import "M80AttributedLabel.h"
#import "UIImage+NIMKit.h"
#import "NIMSessionUnknowContentView.h"
#import "NIMKitUIConfig.h"
#import "NIMKit.h"



@interface NIMMessagCell()<NIMPlayAudioUIDelegate,NIMMessageContentViewDelegate>{
    UILongPressGestureRecognizer *_longPressGesture;
    UIMenuController             *_menuController;
}

@property (nonatomic,strong) NIMMessageModel *model;

@property (nonatomic,copy)   NSArray *customViews;
@end;
@implementation NIMMessagCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (void)makeComponents
{
    //retyrBtn
    self.retryButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.retryButton setImage:[UIImage nim_imageInKit:@"icon_message_cell_error"] forState:UIControlStateNormal];
    [self.retryButton setImage:[UIImage nim_imageInKit:@"icon_message_cell_error"] forState:UIControlStateHighlighted];
    [self.retryButton setFrame:CGRectMake(0, 0, 20, 20)];
    [self.retryButton addTarget:self action:@selector(onRetryMessage:) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:self.retryButton];
    
    //audioPlayedIcon
    self.audioPlayedIcon = [NIMBadgeView viewWithBadgeTip:@""];
    [self.contentView addSubview:self.audioPlayedIcon];
    
    //traningActivityIndicator
    self.traningActivityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0,0,20,20)];
    [self.contentView addSubview:self.traningActivityIndicator];
    
    //headerView
    self.headImageView = [[NIMAvatarImageVi alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
    [self.headImageView addTarget:self action:@selector(onTapAvatar:) forControlEvents:UIControlEventTouchUpInside];
    UILongPressGestureRecognizer *gesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(onLongPressAvatar:)];
    [self.headImageView addGestureRecognizer:gesture];
    [self.contentView addSubview:self.headImageView];
    
    
    //nicknamel
    self.nameLabel = [[UILabel alloc] init];
    self.nameLabel.backgroundColor = [UIColor clearColor];
    self.nameLabel.opaque = YES;
    self.nameLabel.font = [UIFont systemFontOfSize:13.0];
    [self.nameLabel setTextColor:[UIColor darkGrayColor]];
    [self.nameLabel setHidden:YES];
    [self.contentView addSubview:self.nameLabel];
    
    //readlabel
    self.readLabel = [[UILabel alloc] init];
    self.readLabel.backgroundColor = [UIColor clearColor];
    self.readLabel.opaque = YES;
    self.readLabel.font = [UIFont systemFontOfSize:13.0];
    [self.readLabel setTextColor:[UIColor darkGrayColor]];
    [self.readLabel setHidden:YES];
    [self.readLabel setText:NSLocalizedString(@"已读", nil)];
    [self.readLabel setBounds:CGRectMake(0, 0, 28, 20.0)];
    [self.contentView addSubview:self.readLabel];
}

- (void)refresh{
    [self addContentViewIfNotExist];
    [self addUserCustomViews];
    
    self.backgroundColor = [NIMKitUIConfig sharedConfig].globalConfig.backgroundColor;
    
    
    if ([self needShowAvatar])
    {
        [self.headImageView setAvatarByMessage:self.model.message];
    }
    
    if([self needShowNickName])
    {
        NSString *nick = [NIMKitUtil showNick:self.model.message.from inMessage:self.model.message];
        [self.nameLabel setText:nick];
    }
    [self.nameLabel setHidden:![self needShowNickName]];
    
    
    [self.bubbleView refresh:self.model];
    [self.bubbleView setNeedsLayout];
    
    BOOL isActivityIndicatorHidden = [self activityIndicatorHidden];
    if (isActivityIndicatorHidden)
    {
        [self.traningActivityIndicator stopAnimating];
    }
    else
    {
        [self.traningActivityIndicator startAnimating];
    }
    [self.traningActivityIndicator setHidden:isActivityIndicatorHidden];
    [self.retryButton setHidden:[self retryButtonHidden]];
    [self.audioPlayedIcon setHidden:[self unreadHidden]];
    [self.readLabel setHidden:[self readLabelHidden]];
    
    [self setNeedsLayout];
}

- (void)addContentViewIfNotExist
{
    if (self.bubbleView == nil)
    {
        id<NIMCellLayoutConfig> layoutConfig = [[NIMKit sharedKit] layoutConfig];
        NSString *contentStr = [layoutConfig cellContent:self.model];
        NSAssert([contentStr length] > 0, @"should offer cell content class name");
        Class clazz = NSClassFromString(contentStr);
        NIMSessionMessageContentView *contentView =  [[clazz alloc] initSessionMessageContentView];
        NSAssert(contentView, @"can not init content view");
        self.bubbleView = contentView;
        self.bubbleView.delegate = self;
        NIMMessageType messageType = self.model.message.messageType;
        if (messageType == NIMMessageTypeAudio) {
            ((NIMSessionAudioContentView *)self.bubbleView).audioUIDelegate = self;
        }
        [self.contentView addSubview:self.bubbleView];
    }
}

- (void)addUserCustomViews
{
    for (UIView *view in self.customViews) {
        [view removeFromSuperview];
    }
    id<NIMCellLayoutConfig> layoutConfig = [[NIMKit sharedKit] layoutConfig];
    self.customViews = [layoutConfig customViews:self.model];
    
    for (UIView *view in self.customViews) {
        [self.contentView addSubview:view];
    }
}
- (BOOL)needShowAvatar
{
    return self.model.shouldShowAvatar;
}

- (BOOL)needShowNickName
{
    return self.model.shouldShowNickName;
}


- (BOOL)retryButtonHidden
{
    if (!self.model.message.isReceivedMsg) {
        return self.model.message.deliveryState != NIMMessageDeliveryStateFailed;
    } else
    {
        return self.model.message.attachmentDownloadState != NIMMessageAttachmentDownloadStateFailed;
    }
}


- (BOOL)activityIndicatorHidden
{
    if (!self.model.message.isReceivedMsg)
    {
        return self.model.message.deliveryState != NIMMessageDeliveryStateDelivering;
    }
    else
    {
        return self.model.message.attachmentDownloadState != NIMMessageAttachmentDownloadStateDownloading;
    }
}

- (BOOL)unreadHidden {
    if (self.model.message.messageType == NIMMessageTypeAudio) { //音频
        BOOL disable = NO;
        if ([self.model.sessionConfig respondsToSelector:@selector(disableAudioPlayedStatusIcon)]) {
            disable = [self.model.sessionConfig disableAudioPlayedStatusIcon];
        }
        BOOL hideIcon = self.model.message.attachmentDownloadState != NIMMessageAttachmentDownloadStateDownloaded || disable;
        
        return (hideIcon || self.model.message.isOutgoingMsg || [self.model.message isPlayed]);
    }
    return YES;
}

- (BOOL)readLabelHidden
{
    if (self.model.shouldShowReadLabel &&
        [self activityIndicatorHidden] &&
        [self unreadHidden])
    {
        return NO;
    }
    return YES;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
